<template>

    <DeceasedView :data="info" v-if="query.type == 0" v-cloak/>
    <WorshipView :data="info" v-if="query.type == 1" v-cloak/>
    <PhotoView :data="info" v-if="query.type == 2"  v-cloak/>
    <LoadingView v-if="query.type == -1" v-cloak/>
</template>
<script setup name="blessing">
import axios, { baseUrl } from '../utils/http'
//import { checkImgExists, checkVideoExists, checkAudioExists } from '../utils/util'
import WorshipView from '@/views/worship.vue'
import DeceasedView from '@/views/deceased.vue'
import PhotoView from '@/views/swiper.vue'
import LoadingView from '@/views/loading.vue'

import { ref, onMounted, onBeforeUnmount, nextTick,computed } from 'vue'
import { useRoute } from 'vue-router'
import { showFullScreenPrompt } from '../utils/fullscreen';
import { isImage, isVideo } from '@/utils/util'


const param = useRoute();
const list = ref([])
const query = ref({ type: -1 })
const info = ref({})
const cid = ref('')
const tid = ref('');
const first_tid = ref('')
const zid = ref('')
let timer = null

console.log('env', import.meta.env)

const currentView = computed(() => {
  switch (query.value.type) {
    case 0:  return DeceasedView
    case 1:  return WorshipView
    case 2:  return PhotoView
    case -1: return LoadingView
  }
})

function extractFileName(filePath) {
    // 使用 lastIndexOf 找到最后一个斜杠和点
    if (!filePath) return;
    const lastSlashIndex = filePath?.lastIndexOf("/");
    // 如果路径中没有斜杠或点，返回默认值
    if (lastSlashIndex === -1) {
        return filePath
    }
    // 提取文件名和后缀
    const filePathRs = filePath?.slice(lastSlashIndex + 1);
    return filePathRs;
}

async function generateFiles(res) {
    const config = import.meta.env.VITE_PACKAGE_CONFIG;
    const newRes = { ...res };
    const localRes = { ...res };
    if (config == 'local') {
        const bgMater = newRes.BackgroundImage;
        const mater = newRes.BackgroundMaterial;
        const numFile = newRes.CeremonyOrdersID;
        const bgMater_local = numFile + '/' + extractFileName(newRes.BackgroundImage);
        const mater_local = numFile + '/' + extractFileName(newRes.BackgroundMaterial);
        // localRes.BackgroundImage = extractFileName(localRes.BackgroundImage)
        // localRes.BackgroundMaterial = extractFileName(localRes.BackgroundMaterial)
        // localRes.backgroundMusic = extractFileName(localRes.backgroundMusic)
        localRes.BackgroundImageLocal = bgMater_local
        

        if (query.type != 2) { 

            localRes.BackgroundMaterialLocal = mater_local;
        } else {
          localRes.BackgroundMaterialLocal = newRes.BackgroundMaterial?.split(',')?.filter(v => v).map(v => (numFile + '/' + v))
            
        }
        localRes.backgroundMusicLocal = numFile + '/' + extractFileName(newRes.backgroundMusic)
        // if (res.isBackVideo || res.isBackImg) {
        //     let bgRes = null;
        //     if (res.isBackVideo) {
        //         bgRes = await checkVideoExists(bgMater_local)
        //     }
        //     if (res.isBackImg) {
        //         bgRes = await checkImgExists(bgMater_local)
        //     }
        //     if (!bgRes) {
        //         localRes.BackgroundImageLocal = baseUrl + '/' + bgMater;
        //     } else {
        //         localRes.BackgroundImageLocal = bgMater_local
        //     }
        // }
        // if (res.isMaterialImg || res.isMaterialVideo) {

        //     if (query.type != 2) {
        //         let mRes = null;
        //         if (res.isMaterialVideo) {
        //             mRes = await checkVideoExists(mater_local)
        //         }
        //         if (res.isMaterialImg) {
        //             mRes = await checkImgExists(mater_local)
        //         }
        //         if (!mRes) {
        //             localRes.BackgroundMaterialLocal = baseUrl + '/' + mater;
        //         } else {
        //             localRes.BackgroundMaterialLocal = mater_local
        //         }
        //     } else {
        //         let mRes2 = null;
        //         let mater_local2 = newRes.BackgroundMaterial?.split(',')?.[0]
        //         if (res.isMaterialVideo) {
        //             mRes2 = await checkVideoExists(mater_local2)
        //         }
        //         if (res.isMaterialImg) {
        //             mRes2 = await checkImgExists(mater_local2)
        //         }

        //         if (!mRes2) {
        //             localRes.BackgroundMaterialLocal = newRes.BackgroundMaterial?.split(',')?.filter(v => v).map(v => (baseUrl + '/' + v))

        //         } else {
        //             localRes.BackgroundMaterialLocal = newRes.BackgroundMaterial?.split(',')?.filter(v => v).map(v => (numFile + '/' + v))
        //         }
        //     }


        // }
        //const music_on = await checkAudioExists(localRes.backgroundMusic);

        // if (!music_on) {
        //     localRes.backgroundMusicLocal = baseUrl + '/' + newRes.backgroundMusic;
        // } else {
        //     localRes.backgroundMusicLocal = numFile + '/' + extractFileName(newRes.backgroundMusic)
        // }
        //console.log('localRes', localRes)
        return localRes;
    }
    return newRes;
}

const setCjInfo = async (list, res) => {
    const r = list?.filter(v => v.ID == res)[0];
    query.value.type = r?.TemplateType ?? -1;
    //console.log('r', r);
    const objres = await generateFiles(r)
    info.value = { ...objres };
}


// 获取投影播放
const getTemplateIdFn = async (cids) => {
    // const cids = param.query?.cid ?? cid.value
    const tids = param.query?.tid ?? tid.value
    try {
        const res = await axios.getAjaxFn('/SZ_CeremonyTemplate/GetTemplateID', {
            CeremonyOrdersID: cids,
            //TemplateID: tids
        })
        if (res == -2) {
            // 结束投影
            tid.value = '';
            query.value.type = -1;
            return res;
        }
        // if (tid.value != res) {
        //     tid.value = res;
        // }

        return res;
    } catch (error) {
        console.log('getTemplateIdFn', error)
    }

}


const getTemplateList = async (id, tids) => {
    const res = await axios.getAjaxFn('/SZ_CeremonyTemplate/GetCeremonyTemplateList', {
        ID: id
    })
    //let audioUrl = baseUrl + '/' + 'Upload/Tables/SZ_CeremonyTemplate/202410051716142239/纯音乐1.mp3'
    if (!res.length) {
        query.value.type = -1;
        return
    };
    const newData = res.map(v => {

        const isBackImg = isImage(v.BackgroundImage)
        const isMaterialImg = isImage(v.BackgroundMaterial)
        const isBackVideo = isVideo(v.BackgroundImage)
        const isMaterialVideo = isVideo(v.BackgroundMaterial)
        return {
            ...v,
            isBackImg,
            isMaterialImg,
            isBackVideo,
            isMaterialVideo
        }
    })
    tid.value = tids;
    setCjInfo(newData, tids)


}

// 获取展厅下面的礼仪
const getExhibitionHallOrdersFn = async () => {
    const zids = param.query?.zid
    try {
        const res = await axios.getAjaxFn('/SZ_CeremonyOrders/GetChannelExhibitionHallOrders', {
            ChannelExhibitionHallID: zids
        })
        if (!res.length) {
            //clearInterval(timer)
            query.value.type = -1;
            return
        };
        console.log()
        const ysid = res[0].CeremonyOrdersID;
        cid.value = ysid;
        const res_tid = await getTemplateIdFn(ysid);
        if (res_tid == -2) {
            tid.value = '';
            return;
        }

        getTemplateList(ysid, res_tid)

        //console.log('getExhibitionHallOrdersFn', ysid)


    } catch (error) {
        console.log('getExhibitionHallOrdersFn', error)
    }

}


onMounted(async () => {
    //showFullScreenPrompt()
    if (!param.query?.zid) {
        console.error('没有展厅id');
        clearInterval(timer);
        return;
    }

    // await getExhibitionHallOrdersFn()
    // await nextTick()
    // if (param.query?.cid) {
    //     cid.value = param.query?.cid
    // }
    // if (param.query?.tid) {
    //     tid.value = param.query?.tid
    // }
    timer = setInterval(() => {
        getExhibitionHallOrdersFn()
    }, 2 * 1000)

    // getTemplateList(param.query?.cid)
    //getExhibitionHallOrdersFn()


})
onBeforeUnmount(() => {
    clearInterval(timer)
})
</script>
<style lang="less" scoped>
[v-cloak] { display: none }

.fade-enter-active, .fade-leave-active {
  transition: opacity .3s;
}
.fade-enter-from, .fade-leave-to {
  opacity: 0;
}
</style>